# coding=utf-8
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, delete
from common.exemgt.model import ExeMgt
from common.utils.tz import (
    utc_to_local_str
)

@sql_wrapper
def get_exemgt(id):
    if id == 'all':
        exemgt = ExeMgt.query.all()
        exemgt_data = []
        if exemgt:
            for li in exemgt:
                li = li.as_dict()
                li['updated_at'] = utc_to_local_str(li['updated_at']) if li['updated_at'] else ''
                li['created_at'] = utc_to_local_str(li['created_at']) if li['created_at'] else ''
                exemgt_data.append(li)
        return exemgt_data
    else:
        exemgt_data = ExeMgt.query.filter(ExeMgt.id == id).first()
        if exemgt_data:
            return exemgt_data.as_dict()
        else:
            return 'no record found'

@sql_wrapper
def upsert_exemgt(details):
    if 'id' in details:
        id = details['id']
    else:
        id = None
    return upsert(ExeMgt, details, id)

@sql_wrapper
def delete_exemgt(id):
    if id:
        delete = ExeMgt.query.filter(ExeMgt.id == id).first()
        if delete:
            delete.delete()
        else:
            return 'no record found to delete'
        return 'success'
    else:
        return 'error'

